package tree;

import offer.TreeNode;

import java.util.*;

/**
 * 给定一个二叉树，返回其节点值的锯齿形层序遍历。（即先从左往右，再从右往左进行下一层遍历，以此类推，层与层之间交替进行）。
 *
 * 例如：
 * 给定二叉树 [3,9,20,null,null,15,7],
 *
 *     3
 *    / \
 *   9  20
 *     /  \
 *    15   7
 * 返回锯齿形层序遍历如下：
 *
 * [
 *   [3],
 *   [20,9],
 *   [15,7]
 * ]
 * 通过次数18
 *
 */
public class leetCode103_zigzagLevelOrder {
    List<List<Integer>> ans = new ArrayList<>();
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
       if(root == null) return ans;
       build(root);
       return ans;
    }

    public void build(TreeNode root) {
        Deque<TreeNode> deque = new ArrayDeque<>();
        deque.add(root);
        int flag = 0;
        while (!deque.isEmpty()) {
            List<Integer> item = new ArrayList<>();
            int size = deque.size();
            Deque<TreeNode> tmp = new ArrayDeque<>();
            if (flag % 2 == 0) {
                for (int i = 0; i < size; i++) {
                    TreeNode pollFirst = deque.pollFirst();
                    item.add(pollFirst.val);
                    if (pollFirst.left != null) {
                        tmp.addFirst(pollFirst.left);
                    }
                    if (pollFirst.right != null) {
                        tmp.addFirst(pollFirst.right);
                    }
                }
            } else {
                for (int i = 0; i < size; i++) {
                    TreeNode pollFirst = deque.pollFirst();
                    item.add(pollFirst.val);
                    if (pollFirst.right != null) {
                        tmp.addFirst(pollFirst.right);
                    }
                    if (pollFirst.left != null) {
                        tmp.addFirst(pollFirst.left);
                    }
                }
            }
            deque = tmp;
            flag++;
            ans.add(item);
        }

    }

    private static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
